from user.models import Role, Empower, Permission
from pms.common.utils import flatten_view
from user.utils.permission import get_pids_by_rid


def create_role(name):
    new_role = Role(name=name)
    new_role.save()
    return new_role


def update_role(role, view):
    assert isinstance(role, Role)
    argv = flatten_view(view, {
        'name': 'name'
    })
    role.__dict__.update(**argv)
    if 'permissions' in view and view['permissions'] is not None:
        new_pids = set(view['permissions'])
        old_pids = set(get_pids_by_rid(role))
        append_pids = new_pids - old_pids
        remove_pids = old_pids - new_pids
        append_empowers = [Empower(rid=role, pid=Permission.objects.get(id=pid)) for pid in append_pids]
        remove_empowers = [Empower.objects.get(rid=role, pid=Permission.objects.get(id=pid)) for pid in remove_pids]
        for empower in append_empowers:
            empower.save()
        for empower in remove_empowers:
            empower.delete()
    role.save()
    return role
